package cn.jobstart.common.algorithm;

import cn.jobstart.common.SkList;
import org.apache.commons.lang3.StringUtils;

import java.util.*;

/**
 * @author sunke
 * @version 1.0
 * @Description
 * @date 2023-11-01 19:59
 */
public class TextSimilarity {


    public static void main(String[] args) {

    }

    public static double calculateCosineSimilarity(Map<String,String> oneMap,Map<String,String> twoMap){

        String oneText="";

        List<Double> result= SkList.getInstance();
        double sum=0;

        for(String key:oneMap.keySet()){
            double sim=getSimilarity(oneMap.get(key),twoMap.get(key));
            result.add(sim);
            sum+=sim;
        }




        return sum / (result.size());






      /*  for(String value:oneMap.values()){
            oneText+=value+"@@";
        }
        String twoText="";
        for(String value:twoMap.values()){
            twoText+=value+"@@";
        }

        return getSimilarity(oneText,twoText);*/

    //    return calculateCosineSimilarity(oneText,twoText);


    }


    public static double getSimilarity(String str1, String str2) {


        int distance = StringUtils.getLevenshteinDistance(str1, str2);
        int maxLen = Math.max(str1.length(), str2.length());
        double similarity = (maxLen - distance) / (double) maxLen;

        return similarity;

    }


    public static double calculateCosineSimilarity(String text1,String text2){

        Map<String,Integer> wordFrequency1=calculateWordFrequency(text1);
        Map<String,Integer> wordFrequency2=calculateWordFrequency(text2);

        Set<String> unionWords=new HashSet<>();
        unionWords.addAll(wordFrequency1.keySet());
        unionWords.addAll(wordFrequency2.keySet());
        int[] vector1=new int[unionWords.size()];
        int[] vector2=new int[unionWords.size()];
        int i=0;
        for(String word:unionWords){
            if(wordFrequency1.containsKey(word)){
                vector1[i]=wordFrequency1.get(word);
            }
            if(wordFrequency2.containsKey(word)){
                vector2[i]=wordFrequency2.get(word);
            }
            i++;

        }
        double innerProduct=0;
        double normVector1=0;
        double normVector2=0;
        for(int j=0;j<unionWords.size();j++){
            innerProduct+=vector1[j]* vector2[j];
            normVector1+=vector1[j]* vector1[j];
            normVector2+=vector2[j]* vector2[j];
        }
        return innerProduct/(Math.sqrt(normVector1) *Math.sqrt(normVector2));
    }


    private static Map<String,Integer> calculateWordFrequency(String text){
        Map<String,Integer> wordFrequency=new HashMap<>();
        String[] words=text.split("@@");
        for(String word:words){
            if(wordFrequency.containsKey(word)){
                wordFrequency.put(word,wordFrequency.get(word)+1);
            }else{
                wordFrequency.put(word,1);
            }
        }
        return wordFrequency;
    }





}
